package com.up.vms.interfaces.rest.controller;

import com.up.jiasai.spring.annotation.LoginedAuth;
import com.up.vms.application.base.auth.UserSession;
import com.up.vms.application.service.BannerApplicationService;
import com.up.vms.application.service.CategoryApplicationService;
import com.up.vms.application.service.ShortVideoApplicationService;
import com.up.vms.application.service.VideoApplicationService;
import com.up.vms.domain.module.BannerDTO;
import com.up.vms.domain.module.CategoryDTO;
import com.up.vms.domain.module.ShortVideoDTO;
import com.up.vms.domain.module.VideoDTO;
import com.up.vms.domain.vm.entity.Category;
import com.up.vms.domain.vm.entity.ShortVideo;
import com.up.vms.domain.vm.enums.BannerStatus;
import com.up.vms.domain.vm.enums.CategoryStatus;
import com.up.vms.infrastructure.mvc.BaseResponse;
import com.up.vms.infrastructure.mvc.GeneRespDTO;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.infrastructure.util.CommonUtils;
import com.up.vms.interfaces.rest.request.OpVideoRequest;
import com.up.vms.interfaces.rest.request.ShortVideoRequest;
import com.up.vms.interfaces.rest.response.CommonResponse;
import com.up.vms.interfaces.rest.component.QnOssManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "App应用入口", produces = "application/json")
@RequestMapping("/app/v1")
@Slf4j
public class AppController {


    @Autowired
    private VideoApplicationService videoApplicationService;

    @Autowired
    private CategoryApplicationService categoryApplicationService;

    @Autowired
    private ShortVideoApplicationService shortVideoApplicationService;

    @Autowired
    private QnOssManager qnOssManager;

    @Value("${vms.qiniu.temp.bucket}")
    private String tempBucket;


//    @Autowired
//    private AuthUtil authUtil;
//
//    @RequestMapping(value = "/userInfo")
//    public BaseResponse getToken(@RequestParam(value = "id") String id) {
//        CommonResponse commonResponse = new CommonResponse();
//        try {
//            HashMap<String, Object> content = new HashMap<>();
//            content.put("id", id);
//            Map<String, Object> result = authUtil.getToken(content);
//            if (result != null && result.containsKey("resultCode")) {
//                String resultCode = (String) result.get("resultCode");
//                if ("000000".equals(resultCode) && result.containsKey("result")) {
//                    commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
//                    commonResponse.setData(result.get("result"));
//                } else {
//                    commonResponse.setRespCode(new RespCode(ReturnCode.USER_NOT_EXIST));
//                }
//            } else {
//                commonResponse.setRespCode(new RespCode(ReturnCode.REMOTE_AUTH_FAILED));
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
//        }
//
//        return commonResponse;
//    }


    @RequestMapping(value = "/video/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取分类视频列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer"),
            @ApiImplicitParam(name = "categoryId", value = "分类Id", dataType = "Long")
    })
    @ResponseBody
    public BaseResponse videoList(
            @RequestParam(value = "videoName", required = false) String videoName,
            @RequestParam(value = "status", required = false) Integer showVideoMode,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {
        GeneRespDTO<HashMap> geneRespDTO = null;
        CommonResponse commonResponse = new CommonResponse();
        VideoDTO videoDTO = new VideoDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                videoDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                videoDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(videoName)) {
                videoDTO.setVideoName(videoName);
            }
            if (CommonUtils.isNotNull(showVideoMode)) {
                videoDTO.setShowVideoMode(showVideoMode);
            }
            if (CommonUtils.isNotNull(categoryId)) {
                videoDTO.setCategoryId(categoryId);
            }

            videoDTO.setSortColumn("sorting");

            geneRespDTO = videoApplicationService.getVideoListByCategoryId(videoDTO);

            commonResponse.setData(geneRespDTO.getData());
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取分类视频列表失败：{}", e.getMessage(), e.getCause());
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    /**
     * 视频详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/video/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取视频详情")
    @ResponseBody
    public BaseResponse getById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = videoApplicationService.queryAppById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    /**
     * 视频详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/video/detail/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取视频详情")
    @ResponseBody
    public BaseResponse getVideoById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = videoApplicationService.queryAppById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }


    @RequestMapping(value = "/short/detail/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取视频详情")
    @ResponseBody
    public BaseResponse getShortById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = shortVideoApplicationService.queryAppById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }


    /**
     * 分类列表，条件是（显示的），status =
     * @param category
     * @param status
     * @param index
     * @param size
     * @return
     */
    @RequestMapping(value = "/category/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取分类列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse getCategoryList(
            @RequestParam(value = "category", required = false) String category,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {
        GeneRespDTO<HashMap> geneRespDTO = null;
        CommonResponse commonResponse = new CommonResponse();
        CategoryDTO categoryDTO = new CategoryDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                categoryDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                categoryDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(category)) {
                categoryDTO.setCategory(category);
            }

            categoryDTO.setStatus(CategoryStatus.AVAILABLE.code);

            geneRespDTO = categoryApplicationService.getCategoryList(categoryDTO);

            Map<String, Object> map = geneRespDTO.getData();
            List<Category> list = new ArrayList<>();

            if (CommonUtils.isNotNull(map) && map.containsKey("content") && CommonUtils.isNotNull(map.get("content"))) {

                try {
                    List<Category> content = (List<Category>) map.get("content");

                    for (Category cate : content) {
                        list.add(cate);
                    }

                } catch (Exception e) {
                    log.warn("转换失败：" + e.getMessage());
                }
            }
            Category category1 = new Category();
            category1.setCategory("推荐");
            category1.setCategoryId(-1L);
            list.add(0, category1);

            Category category2 = new Category();
            category2.setCategoryId(-2L);
            category2.setCategory("短视频");
            list.add(1, category2);

            map.put("content", list);
            map.put("totalRecords", (long)map.get("totalRecords") + 2);

            commonResponse.setData(geneRespDTO.getData());
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取分类列表失败：{}", e.getMessage(), e.getCause());
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    /**
     * 轮播图列表,条件
     */

    @Autowired
    private BannerApplicationService bannerApplicationService;

    @RequestMapping(value = "/banner/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取轮播图列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse getBannerList(
            @RequestParam(value = "bannerName", required = false) String bannerName,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {
        GeneRespDTO<HashMap> geneRespDTO = null;
        CommonResponse campaignListResponse = new CommonResponse();
        BannerDTO bannerDTO = new BannerDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                bannerDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                bannerDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(bannerName)) {
                bannerDTO.setBannerName(bannerName);
            }
            bannerDTO.setStatus(BannerStatus.AVAILABLE.code);

            geneRespDTO = bannerApplicationService.getBannerList(bannerDTO);

            campaignListResponse.setData(geneRespDTO.getData());
            campaignListResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取轮播图列表失败：{}", e.getMessage(), e.getCause());
            campaignListResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return campaignListResponse;
    }

    /**
     * 我的视频列表 token
     */
    @RequestMapping(value = "/short/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取短视频列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse getShortVideoList(
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "showVideoMode", required = false) Integer showVideoMode,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size,
            @LoginedAuth UserSession userSession) {
        GeneRespDTO<HashMap> geneRespDTO = null;
        CommonResponse campaignListResponse = new CommonResponse();
        ShortVideoDTO shortVideoDTO = new ShortVideoDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                shortVideoDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                shortVideoDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(status)) {
                shortVideoDTO.setStatus(status);
            }
            if (CommonUtils.isNotNull(categoryId)) {
                shortVideoDTO.setCategoryId(categoryId);
            }
            if (CommonUtils.isNotNull(showVideoMode)) {
                shortVideoDTO.setShowVideoMode(showVideoMode);
            }
            if (CommonUtils.isNull(userSession)) {
                throw new Exception("user need login");
            } else {
                shortVideoDTO.setCreator(userSession.getToken());
            }

            geneRespDTO = shortVideoApplicationService.getShortVideoList(shortVideoDTO);

            campaignListResponse.setData(geneRespDTO.getData());
            campaignListResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取短视频列表失败：{}", e.getMessage(), e.getCause());
            campaignListResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return campaignListResponse;
    }

    /**
     * 删除视频 token
     */
    @RequestMapping(value = "/short/{shortId}/delete", method = RequestMethod.PUT)
    public BaseResponse delete(@PathVariable(value = "shortId") Long shortId, @LoginedAuth UserSession userSession) {
        CommonResponse response = new CommonResponse();
        try {
            if (CommonUtils.isNull(userSession)) {
                throw new Exception("user need login");
            }

            GeneRespDTO geneRespDTO = shortVideoApplicationService.delete(shortId, userSession.getToken());

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    /**
     * 视频上传 token
     */
    @RequestMapping(value = "/video/upToken", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse upToken(@RequestParam(value = "bucket", required = false) String bucket) {
        CommonResponse commonResponse = new CommonResponse();
        try {

            if (CommonUtils.isNull(bucket)) {
                bucket = tempBucket;
            }
            String upToken = qnOssManager.upToken(bucket);

            Map<String, Object> map = new HashMap();
            map.put("token", upToken);

            commonResponse.setData(map);
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
        }
        return commonResponse;
    }


    /**
     * 视频保存 token
     */
    @RequestMapping(value = "/short/save", method = RequestMethod.POST)
    public BaseResponse saveBanner(@RequestBody ShortVideoRequest request, @LoginedAuth UserSession userSession) {
        CommonResponse response = new CommonResponse();
        try {
            ShortVideo shortVideo = convertFromRequest(request, userSession);

            GeneRespDTO geneRespDTO = shortVideoApplicationService.saveShortVideo(shortVideo);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    private ShortVideo convertFromRequest(ShortVideoRequest request, UserSession userSession) {
        ShortVideo shortVideo = new ShortVideo();

        if (CommonUtils.isNotNull(request.getShortId())) {
            shortVideo.setShortId(request.getShortId());
        }

        shortVideo.setShortName(request.getShortName());
        shortVideo.setShortDesc(request.getShortDesc());
        shortVideo.setShortUrl(request.getShortUrl());
        shortVideo.setTelephone(userSession.getPhoneNum());
        shortVideo.setUploader(userSession.getUserName());
        shortVideo.setCreator(userSession.getToken());

        shortVideo.setCategoryId(request.getCategoryId());
        shortVideo.setCategory(request.getCategory());
        shortVideo.setShowMode(request.getShowMode());
        shortVideo.setShowVideoMode(request.getShowVideoMode());
        shortVideo.setShowImage(request.getShowImage());
        shortVideo.setSorting(request.getSorting());
        shortVideo.setRecommendFlag(request.getRecommendFlag());

        return shortVideo;
    }

    /**
     * 转码请求
     */
    @RequestMapping(value = "/video/pfop", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse operateVideoFile(@RequestBody OpVideoRequest request) {
        CommonResponse commonResponse = new CommonResponse();
        try {
            if (CommonUtils.isNotNull(request.getKey())) {
                Map<String, Object> map = qnOssManager.operateFile(request.getKey());
                commonResponse.setData(map);
                commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
            } else {
                commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), "key is null"));
            }
        } catch (Exception e) {
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), e.getMessage()));
        }

        return commonResponse;
    }

    /**
     * 转码进度
     */
    @RequestMapping(value = "/video/pfop/status", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse pfopStatus(@RequestParam(value = "id") String id) {
        CommonResponse commonResponse = new CommonResponse();
        List<String> idList = new ArrayList<>();

        if (id.contains(";")) {
            String[] ids = id.split(";");
            for (String pId : ids) {
                idList.add(pId);
            }
        } else {
            idList.add(id);
        }

        List<Map<String, Object>> retList = new ArrayList<>();
        for (String pId : idList) {
            Map<String, Object> map = new HashMap();
            try {
                map = qnOssManager.pfopStatus(pId);
            } catch (Exception e) {
                map.put("persistentId", pId);
                map.put("status", e.getMessage());
            }
            retList.add(map);
        }

        commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));
        commonResponse.setData(retList);

        return commonResponse;
    }
}
